package com.lablzh.gdxy.config.verifyCode;

import com.lablzh.gdxy.component.VerifyCodeCache;
import com.lablzh.gdxy.config.MyAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class VerifyCodeFilter extends OncePerRequestFilter {
    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(httpServletRequest.getRequestURI().equals("/login")&&httpServletRequest.getMethod().equalsIgnoreCase("post")){
            try {
                validate(httpServletRequest);
            } catch (VerifyCodeException e) {
                myAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validate(HttpServletRequest request) throws ServletRequestBindingException, VerifyCodeException {
        String uuid=request.getParameter("uuid");
        String captcha = ServletRequestUtils.getStringParameter(request, "captcha");
        String code = VerifyCodeCache.getCode(uuid);//服务器验证码
        System.out.println("缓存中该uuid的验证码是："+code);
        VerifyCodeCache.deleteCodeFromCache(uuid);
       if(code==null||!code.equalsIgnoreCase(captcha)){
            throw new VerifyCodeException("验证码不正确！");
        }
    }
}
